import { t } from 'i18next'
import { useEffect } from 'react'
import shallow from 'zustand/shallow'
import { ListTranslator } from './translator'
import { Alert } from '@/components/Alert'
import { findIndex } from 'lodash-es'
import { useChasingStore } from './store'
import { differenceBy } from 'lodash-es'
import { ListTopActionItem } from '@/components/List/ListTop'
import { DropData } from '@/api/manager/type'
import { MtEntity } from '@/api/manager/mt'
import { useMccStore } from '../../store'
import { actionButtonsCancel } from '../../store.actionButton'

export const useData = () => {
	const { list, fetchChasingList, update, postChasingList } = useChasingStore(
		(state) => ({
			list: state.list,
			update: state.update,
			fetchChasingList: state.fetchChasingList,
			postChasingList: state.postChasingList,
		}),
		shallow
	)
	useEffect(() => {
		fetchChasingList()
	}, [])
	//拖拽
	const handleDrop = (dataTransfer: DropData, index: number) => {
		if (dataTransfer && dataTransfer.data && dataTransfer.data.mt) {
			let mt = dataTransfer.data.mt
			let isMt = mt.isMt
			//只能终端才能加入追呼设置，级联会议不可以
			if (!(dataTransfer.from === 'chasing' || isMt)) {
				return
			}
			// 添加列表
			let mts = ListTranslator([mt as MtEntity])
			if (dataTransfer.from !== 'chasing') {
				const insertList = differenceBy(mts, list, (x) => x.mtKey)
				let newList = [...list.slice(0, index), ...insertList, ...list.slice(index)]
				update({ list: newList })
			} else {
				const baseList = differenceBy(list, mts, (x) => x.mtKey)
				let insertToBaseIndex = index
				const baseListMtKeys = baseList.map((l) => l.mtKey)
				const nextFirstBaseListIndex = findIndex(list, (l) => baseListMtKeys.includes(l.mtKey), index)
				if (nextFirstBaseListIndex === -1) {
					insertToBaseIndex = baseList.length
				} else {
					insertToBaseIndex = baseList.findIndex((l) => l.mtKey === list[nextFirstBaseListIndex].mtKey)
				}
				update({
					list: [...baseList.slice(0, insertToBaseIndex), ...mts, ...baseList.slice(insertToBaseIndex)],
				})
			}
		}
	}
	const topActions: ListTopActionItem[] = [
		{
			text: t('删除'),
			onClick: () => {
				const unCheckedList = list.filter((l) => !l.status.checked)
				const checkedList = list.filter((l) => l.status.checked)
				if (checkedList.length === 0) {
					Alert(t('请选择人员'))
					return
				}
				update({ list: unCheckedList })
			},
		},
		{
			text: t('清空'),
			onClick: () => {
				update({ list: [] })
			},
		},
	]
	const handleBack = () => {
		useMccStore.getState().setCurPage('mcc_main')
		actionButtonsCancel()
	}
	const handleSave = () => {
		postChasingList()
	}
	const handleOrder = () => {}
	return {
		handleDrop,
		topActions,
		handleBack,
		handleSave,
		handleOrder,
	}
}
